from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin, RetrieveCacheResponseMixin

from areas import serializers
from areas.models import Area


# GET /areas/
class AreasViews(ListCacheResponseMixin, ListAPIView):
    queryset = Area.objects.filter(parent=None)
    serializer_class = serializers.AreaSerializers


# GET /areas/(?P<pk>\d+)/
class SubAreasViews(RetrieveCacheResponseMixin, RetrieveAPIView):
    queryset = Area.objects.all()
    serializer_class = serializers.SubAreaSerializers


# 优化以上视图集
class AreasViewsSet(ReadOnlyModelViewSet):

    def get_serializer_class(self):
        if self.action == 'list':
            return serializers.AreaSerializers
        else:
            return serializers.SubAreaSerializers

    def get_queryset(self):
        if self.action == 'list':
            queryset = Area.objects.filter(parent=None)
            return queryset
        else:
            queryset = Area.objects.all()
            return queryset
